#pragma once
#include <iostream>
#include <string>
#include <memory>
#include "Socket.hpp"
#include <functional>
#include <jsoncpp/json/json.h>

using namespace SocketModule;
class Request
{
public:
    Request()
    {
    }
    Request(int x, int y, char oper)
        : _x(x),
          _y(y),
          _oper(oper)
    {
    }
    // 序列化
    std::string Serialize()
    {
        Json::Value root;
        root["x"] = _x;
        root["y"] = _y;
        root["oper"] = _oper;

        Json::FastWriter writer;
        std::string s = writer.write(root);
        return s;
    }
    // 反序列化
    bool Deserialize(std::string &in)
    {
        Json::Value root;
        Json::Reader reader;
        bool ok = reader.parse(in, root);
        if (ok)
        {
            _x = root["x"].asInt();
            _y = root["y"].asInt();
            _oper = root["oper"].asInt();
        }
        return ok;
    }
    ~Request() {}
    int X() { return _x; }
    int Y() { return _y; }
    char Oper() { return _oper; }

private:
    int _x;
    int _y;
    char _oper;
};
class Response
{
public:
    Response() {}
    Response(int result, int code) : _result(result), _code(code)
    {
    }
    std::string Serialize()
    {
        Json::Value root;
        root["result"] = _result;
        root["code"] = _code;

        Json::FastWriter writer;
        return writer.write(root);
    }
    bool Deserialize(std::string &in)
    {
        Json::Value root;
        Json::Reader reader;
        bool ok = reader.parse(in, root);
        if (ok)
        {
            _result = root["result"].asInt();
            _code = root["code"].asInt();
        }
        return ok;
    }
    void SetResult(int res)
    {
        _result = res;
    }
    void SetCode(int code)
    {
        _code = code;
    }
    void ShowResult()
    {
        std::cout<<"计算结果是："<<_result<<"["<<_code<<"]"<<std::endl;
    }
    ~Response() {}

private:
    int _result; // 运算结果，无法区分清楚应答是计算结果，还是异常值
    int _code;   // 0:sucess, 1,2,3,4->不同的运算异常的情况
};
const std::string sep = "\r\n";
using func_t = std::function<Response(Request &req)>;
class Protocol
{
public:
    Protocol()
    {
    }
    Protocol(func_t func) : _func(func)
    {
    }
    std::string Encode(const std::string &jsonstr)
    {
        std::string len = std::to_string(jsonstr.size());
        return len + sep + jsonstr + sep;
    }
    // 50\r\n{"x": 10, "y" : 20, "oper" : '+'}\r\n
    bool Decode(std::string &buffer, std::string *package)
    {
        ssize_t pos = buffer.find(sep);
        if (pos == std::string::npos)
            return false;
        std::string package_len_str = buffer.substr(0, pos);
        int packagelen = std::stoi(package_len_str);
        int target_len = package_len_str.size() + packagelen + 2 * sep.size();
        if (buffer.size() < target_len)
            return false;
        *package = buffer.substr(pos + sep.size(), packagelen);
        buffer.erase(0, target_len);
        return true;
    }
    void GetRequest(std::shared_ptr<Socket> &sock, InetAddr &clinet)
    {
        std::string buffer_queue;
        while (1)
        {
            int n = sock->Recv(&buffer_queue);
            if (n > 0)
            {
                std::cout << "--------------request_buffer----------------" << std::endl;
                std::cout << buffer_queue << std::endl;
                std::cout << "-------------------------------------------" << std::endl;
                std::string json_package;
                while (Decode(buffer_queue, &json_package))
                {
                    LOG(LogLevel::DEBUG) << clinet.StringAddr() << "请求：" << json_package;
                    Request req;
                    bool ok = req.Deserialize(json_package);
                    if (!ok)
                        continue;
                    // 3.
                    Response resp = _func(req);
                    // 4.序列化
                    std::string json_str = resp.Serialize();
                    // 5.添加自定义长度
                    std::string send_str = Encode(json_str);
                    // 6.直接发送
                    sock->Send(send_str);
                }
                // bool ret = Decode(buffer_queue, &json_package);
                // if (!ret)
                //     continue;
                // Request req;
                // bool ok = req.Deserialize(json_package);
                // if (!ok)
                // {
                //     continue;
                // }
                // Response resp = _func(req);
                // // 序列化
                // std::string json_str = req.Serialize();
                // // 添加自定义长度
                // std::string send_str = Encode(json_str);
                // // 直接发送
                // sock->Send(send_str);
            }
            else if (n == 0)
            {
                LOG(LogLevel::INFO) << "client" << clinet.StringAddr() << "Quit";
                break;
            }
            else
            {
                LOG(LogLevel::WARNING) << "client" << clinet.StringAddr() << ",recv error";
                break;
            }
        }
    }
    bool GetResponse(std::shared_ptr<Socket> &client, std::string &resp_buffer, Response *resq)
    {
        while (1)
        {
            int n = client->Recv(&resp_buffer);
            if (n > 0)
            {
                std::string json_package;
                while (Decode(resp_buffer, &json_package))
                {
                    resq->Deserialize(json_package);
                }
                return true;
            }
            else if (n == 0)
            {
                std::cout << "server quit" << std::endl;
                return false;
            }
            else
            {
                std::cout << "recv error" << std::endl;
                return false;
            }
        }
    }
    std::string BulidRequestString(int x, int y, char oper)
    {
        Request req(x, y, oper);
        std::string json_req = req.Serialize();
        return Encode(json_req);
    }
    ~Protocol() = default;

private:
    //  Request _req;
    //  Response __resp;
    func_t _func;
};